#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown到HTML转换器

功能：
- 将单个或多个Markdown文件转换为HTML
- 支持CommonMark语法
- 代码语法高亮
- 自动生成目录
- 响应式设计
- 自定义样式支持
"""

import os
import re
import sys
import argparse
import markdown
from markdown.extensions import toc, codehilite, fenced_code, tables

def read_markdown_file(file_path):
    """读取Markdown文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        print(f"错误：无法读取文件 {file_path} - {str(e)}")
        return None

def extract_title(markdown_content):
    """从Markdown内容中提取标题"""
    match = re.search(r'^#\s+(.+)$', markdown_content, re.MULTILINE)
    if match:
        return match.group(1)
    return "文档"

def generate_html(markdown_content, title, enable_toc=True):
    """将Markdown内容转换为HTML"""
    # 配置Markdown扩展
    extensions = ['markdown.extensions.extra']
    extension_configs = {}
    
    # 添加目录扩展
    if enable_toc:
        extensions.append('markdown.extensions.toc')
        extension_configs['markdown.extensions.toc'] = {
            'title': '目录',
            'toc_depth': '1-6',
            'permalink': False,
        }
    
    # 添加代码高亮
    extensions.append('markdown.extensions.codehilite')
    extension_configs['markdown.extensions.codehilite'] = {
        'css_class': 'highlight',
        'pygments_style': 'default',
        'noclasses': False,
    }
    
    # 创建Markdown实例并转换
    md = markdown.Markdown(extensions=extensions, extension_configs=extension_configs)
    html_content = md.convert(markdown_content)
    toc_html = md.toc if enable_toc else ''
    
    # 基础CSS样式
    css_style = '''
    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        line-height: 1.6;
        color: #333;
        max-width: 1000px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f8f9fa;
    }
    .paper {
        background: white;
        padding: 40px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1, h2, h3, h4, h5, h6 {
        color: #2c3e50;
        margin-top: 1.5em;
        margin-bottom: 0.5em;
    }
    h1 { font-size: 2em; border-bottom: 2px solid #3498db; padding-bottom: 0.3em; }
    h2 { font-size: 1.5em; border-bottom: 1px solid #eee; }
    a { color: #3498db; text-decoration: none; }
    a:hover { text-decoration: underline; }
    ul, ol { margin-left: 2em; }
    pre { background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
    code { font-family: Consolas, Monaco, 'Andale Mono', monospace; }
    table { border-collapse: collapse; width: 100%; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
    th { background-color: #f2f2f2; }
    blockquote { border-left: 4px solid #3498db; padding-left: 1em; margin: 1em 0; color: #666; }
    img { max-width: 100%; height: auto; }
    .toc { background: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 30px; }
    .toc h2 { margin-top: 0; }
    .toc ul { list-style-type: none; }
    .toc ul ul { margin-left: 1.5em; }
    @media (max-width: 768px) {
        body { padding: 10px; }
        .paper { padding: 20px; }
    }
    '''
    
    # 生成完整HTML
    html_template = f'''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <meta name="description" content="{title}">
    <style>{css_style}</style>
</head>
<body>
    <div class="paper">
        {toc_html}
        <main>
            {html_content}
        </main>
    </div>
    <script>
        // 平滑滚动到锚点
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {{
            anchor.addEventListener('click', function (e) {{
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {{
                    target.scrollIntoView({{ behavior: 'smooth' }});
                }}
            }});
        }});
    </script>
</body>
</html>
'''
    
    return html_template

def write_html_file(html_content, output_path):
    """将HTML内容写入文件"""
    try:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        return True
    except Exception as e:
        print(f"错误：无法写入文件 {output_path} - {str(e)}")
        return False

def convert_single_file(input_file, output_file=None, enable_toc=True):
    """转换单个Markdown文件"""
    print(f"正在处理文件: {input_file}")
    
    # 读取Markdown内容
    markdown_content = read_markdown_file(input_file)
    if not markdown_content:
        return False
    
    # 提取标题
    title = extract_title(markdown_content)
    
    # 生成HTML内容
    html_content = generate_html(markdown_content, title, enable_toc)
    
    # 确定输出文件路径
    if not output_file:
        base_name = os.path.splitext(os.path.basename(input_file))[0]
        output_file = os.path.join(os.path.dirname(input_file), f"{base_name}.html")
    
    # 写入HTML文件
    success = write_html_file(html_content, output_file)
    
    if success:
        print(f"转换成功！HTML文件已保存至: {output_file}")
    
    return success

def main():
    """主函数"""
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='将Markdown文件转换为HTML')
    parser.add_argument('input', help='输入文件路径')
    parser.add_argument('-o', '--output', help='输出文件路径')
    parser.add_argument('--no-toc', action='store_true', help='禁用目录生成')
    
    args = parser.parse_args()
    
    # 检查输入路径是否存在
    if not os.path.exists(args.input):
        print(f"错误：输入路径 '{args.input}' 不存在")
        return
    
    # 处理单个文件
    if os.path.isfile(args.input):
        convert_single_file(args.input, args.output, not args.no_toc)

if __name__ == '__main__':
    main()
